"use client"

import { useState, useEffect, useRef } from "react"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { AlbumCard } from "@/components/album-card"
import { SongCard } from "@/components/song-card"
import type { Album } from "@/types/album"
import type { Song } from "@/types/song"
import { Loader2, ChevronLeft, ChevronRight } from "lucide-react"
import { fetchNewAlbums, fetchNewSongs } from "@/lib/api-client"
import {toast} from "@/components/ui/use-toast";
import { usePlayer } from "@/contexts/player-context"

export default function NewPage() {
    const [newAlbums, setNewAlbums] = useState<Album[]>([])
    const [newSongs, setNewSongs] = useState<Song[]>([])
    const [isLoadingAlbums, setIsLoadingAlbums] = useState(true)
    const [isLoadingSongs, setIsLoadingSongs] = useState(true)
    const [error, setError] = useState<string | null>(null)
    const [userId, setUserId] = useState<string | undefined>(undefined)
    const [activeTab, setActiveTab] = useState("albums")
    const [currentPlayingSong] = useState<number | null>(null)
    const audioRef = useRef<HTMLAudioElement | null>(null)
    const {  playSong } = usePlayer()
    // Pagination for albums
    const [albumsCurrentPage, setAlbumsCurrentPage] = useState(1)
    const [albumsTotalPages, setAlbumsTotalPages] = useState(1)
    const albumsPerPage = 5

    // Pagination for songs
    const [songsCurrentPage, setSongsCurrentPage] = useState(1)
    const [songsTotalPages, setSongsTotalPages] = useState(1)
    const songsPerPage = 5

    // Get user ID from localStorage on component mount
    useEffect(() => {
        const storedUserId = localStorage.getItem("userId")
        if (storedUserId) {
            setUserId(storedUserId)
        }

        // Create audio element
        audioRef.current = new Audio()

        // Cleanup on unmount
        return () => {
            if (audioRef.current) {
                audioRef.current.pause()
                audioRef.current = null
            }
        }
    }, [])

    // Fetch new albums from API with pagination
    useEffect(() => {
        const getNewAlbums = async () => {
            setIsLoadingAlbums(true)
            try {
                const response = await fetchNewAlbums({
                    page: albumsCurrentPage,
                    limit: albumsPerPage,
                })

                setNewAlbums(response.items)
                setAlbumsTotalPages(Math.ceil(response.total / albumsPerPage))
                setError(null)
            } catch (err) {
                console.error("获取新专辑失败:", err)
                setError("获取新专辑失败，请稍后再试")
            } finally {
                setIsLoadingAlbums(false)
            }
        }

        getNewAlbums()
    }, [albumsCurrentPage, albumsPerPage])

    // Fetch new songs from API with pagination
    useEffect(() => {
        const getNewSongs = async () => {
            setIsLoadingSongs(true)
            try {
                const response = await fetchNewSongs({
                    page: songsCurrentPage,
                    limit: songsPerPage,
                })

                setNewSongs(response.items)
                setSongsTotalPages(Math.ceil(response.total / songsPerPage))
                setError(null)
            } catch (err) {
                console.error("获取新歌曲失败:", err)
                setError("获取新歌曲失败，请稍后再试")
            } finally {
                setIsLoadingSongs(false)
            }
        }

        getNewSongs()
    }, [songsCurrentPage, songsPerPage])

    // Album pagination handlers
    const handleAlbumsPrevPage = () => {
        if (albumsCurrentPage > 1) {
            setAlbumsCurrentPage(albumsCurrentPage - 1)
        }
    }

    const handleAlbumsNextPage = () => {
        if (albumsCurrentPage < albumsTotalPages) {
            setAlbumsCurrentPage(albumsCurrentPage + 1)
        }
    }

    // Song pagination handlers
    const handleSongsPrevPage = () => {
        if (songsCurrentPage > 1) {
            setSongsCurrentPage(songsCurrentPage - 1)
        }
    }

    const handleSongsNextPage = () => {
        if (songsCurrentPage < songsTotalPages) {
            setSongsCurrentPage(songsCurrentPage + 1)
        }
    }


    return (
        <div className="container mx-auto px-4 py-6">
            <Tabs defaultValue="albums" value={activeTab} onValueChange={setActiveTab} className="w-full">
                <TabsList className="mb-6">
                    <TabsTrigger value="albums" className="text-lg px-6">
                        新专辑
                    </TabsTrigger>
                    <TabsTrigger value="songs" className="text-lg px-6">
                        新歌曲
                    </TabsTrigger>
                </TabsList>

                <TabsContent value="albums">
                    {isLoadingAlbums ? (
                        <div className="flex justify-center items-center h-60">
                            <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
                        </div>
                    ) : error ? (
                        <div className="flex justify-center items-center h-60 text-red-500">{error}</div>
                    ) : (
                        <div className="relative">
                            {/* 左侧翻页按钮 - 第一页不显示 */}
                            {albumsCurrentPage > 1 && (
                                <button
                                    onClick={handleAlbumsPrevPage}
                                    className="absolute left-[-20px] top-[50%] transform -translate-y-1/2 z-10 bg-white rounded-full shadow-lg p-2 hover:bg-gray-100 transition-colors"
                                    aria-label="上一页"
                                >
                                    <ChevronLeft className="h-6 w-6 text-primary" />
                                </button>
                            )}

                            {/* 专辑列表 */}
                            <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-6">
                                {newAlbums.map((album) => (
                                    <AlbumCard key={album.id} album={album} />
                                ))}
                            </div>

                            {/* 右侧翻页按钮 */}
                            {albumsCurrentPage < albumsTotalPages && (
                                <button
                                    onClick={handleAlbumsNextPage}
                                    className="absolute right-[-20px] top-[50%] transform -translate-y-1/2 z-10 bg-white rounded-full shadow-lg p-2 hover:bg-gray-100 transition-colors"
                                    aria-label="下一页"
                                >
                                    <ChevronRight className="h-6 w-6 text-primary" />
                                </button>
                            )}
                        </div>
                    )}
                </TabsContent>

                <TabsContent value="songs">
                    {isLoadingSongs ? (
                        <div className="flex justify-center items-center h-60">
                            <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
                        </div>
                    ) : error ? (
                        <div className="flex justify-center items-center h-60 text-red-500">{error}</div>
                    ) : (
                        <div className="relative">
                            <div className="space-y-2">
                                {newSongs.map((song,index) => (
                                    <SongCard
                                        key={song.id}
                                        index={index+1}
                                        song={song}
                                        userId={userId}
                                        onPlay={() => {
                                            const songWithMetadata = {
                                                ...song,
                                                artists: song.artists,
                                                coverImage: song.cover,
                                                url: `/api/stream/${song.id}`,
                                            }
                                            // Change from addToQueue to playSong for immediate playback
                                            playSong(songWithMetadata)
                                            toast({
                                                title: "开始播放",
                                                description: `${song.title} - ${song.artists}`,
                                            })
                                        }}
                                        isPlaying={currentPlayingSong === song.id}
                                    />
                                ))}
                            </div>

                            {/* 左侧翻页按钮 - 第一页不显示 */}
                            {songsCurrentPage > 1 && (
                                <button
                                    onClick={handleSongsPrevPage}
                                    className="absolute left-[-20px] top-[50%] transform -translate-y-1/2 z-10 bg-white rounded-full shadow-lg p-2 hover:bg-gray-100 transition-colors"
                                    aria-label="上一页"
                                >
                                    <ChevronLeft className="h-6 w-6 text-primary" />
                                </button>
                            )}

                            {/* 右侧翻页按钮 */}
                            {songsCurrentPage < songsTotalPages && (
                                <button
                                    onClick={handleSongsNextPage}
                                    className="absolute right-[-20px] top-[50%] transform -translate-y-1/2 z-10 bg-white rounded-full shadow-lg p-2 hover:bg-gray-100 transition-colors"
                                    aria-label="下一页"
                                >
                                    <ChevronRight className="h-6 w-6 text-primary" />
                                </button>
                            )}
                        </div>
                    )}
                </TabsContent>
            </Tabs>
        </div>
    )
}

